<template>
  <el-form ref="form" :rules="rules" :model="form" label-width="80px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username"></el-input>
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password"></el-input>
    </el-form-item>
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="form.mobile"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">立即创建</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>

    <h1 @click="domHandle" ref="h1Dom">我是h1</h1>
  </el-form>
</template>
<script>
export default {
  data() {
    var validateMobile = (rule, value, callback) => {
      /* 目标：定义手机号的正则   然后手机号匹配正则
      匹配成功：直接走     true
      不成功：请输入合法手机号   false
       */
      var reg =
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      // reg.test()   ==》返回一个bool
      if (!reg.test(value)) {
        //  value    就是表单输入值
        callback(new Error('请输入合法手机号'))
      } else {
        //  满足校验规则  就不需要有红色提示了
        // if (this.ruleForm.checkPass !== '') {
        //   this.$refs.ruleForm.validateField('checkPass')
        // }
        callback()
      }
    }

    return {
      form: {
        username: '',
        password: '123456',
        mobile: '110',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 4, message: '长度在 3 到 4 个字符', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' },
        ],
      },
    }
  },

  created() {
    console.log(this, 'eForm')
  },
  methods: {
    onSubmit() {
      console.log('submit!')
      this.$refs['form'].validate((valid) => {
        console.log(valid) //  返回的是满足校验成功或者不成功的布尔值
        if (valid) {
          //  校验成功   可以发送请求了===只要有一个校验不满足 就不发请求
          alert('ok')
        } else {
          //  校验不成功
          alert('error')
        }
      })
    },
    domHandle() {
      console.log(this.$refs['h1Dom'])
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
  },
}
</script>